
#include "messagequeue.h"

MessageQueue* MessageQueue::_instance = nullptr;

MessageQueue::MessageQueue() {
}

MessageQueue::~MessageQueue() {
	_mapMessageHolders.clear();
}

MessageQueue* MessageQueue::getInstance() {
	if(!_instance) {
		_instance = new MessageQueue();
		_instance->init();
	}

	return _instance;
}

void MessageQueue::init() {
	
}

void MessageQueue::send(const GameMessage& msg) {
	if(strcmp(msg.receiver, "all") == 0) {
		for(auto item : _mapMessageHolders) {
			item.second.push(msg);
		}

	} else {
		auto it = _mapMessageHolders.find(msg.receiver);
		if(it == _mapMessageHolders.end()) {
			queue<GameMessage> q;
			q.push(msg);
			_mapMessageHolders.insert(make_pair(msg.receiver, q));
		} else {
			it->second.push(msg);
		}
	}
}

GameMessage * MessageQueue::peek(const char* receiver) {
	auto it = _mapMessageHolders.find(receiver);
	if(it == _mapMessageHolders.end()) {
		return nullptr;
	} 
	
	queue<GameMessage>& q = it->second;
	if(q.empty()) {
		return nullptr;
	}

	return &(q.front());
}

void MessageQueue::pop(const char* receiver) {
	auto it = _mapMessageHolders.find(receiver);
	if(it != _mapMessageHolders.end()) {
		queue<GameMessage>& q = it->second;
		if(!q.empty()) {
			q.pop();
		}
	}
}

void MessageQueue::clear(const char* target) {
	if(strcmp(target, "all") == 0) {
		_mapMessageHolders.clear();
	} else {
		auto it = _mapMessageHolders.find(target);
		if(it != _mapMessageHolders.end()) {
			queue<GameMessage>& q = it->second;
			while(!q.empty()) {
				q.pop();
			}
		}
	}
}
